/**
 * Created by Li Wending on 2016/11/17.
 */
(function() {
	"use strict";
	app.service("meterService", function() {
		// 生成参数对
		this.construcPara = function(name, value) {
			var para = {};
			var paramObj = {};
			para[name] = value;
			paramObj.param = para;
			paramObj.sign = 'EQ';
			return paramObj;
		}

		// 饼图函数
		this.eChartsSeIn = function(divid) {
			var dataRead=[];
			var oneDay = 2000;
			var now = +new Date();
			var value;
			var nowtime;
			var i;
			var ctime =  new Date().getTime();
			function readData() {
				now = new Date(ctime);
				value = Math.random()*100;
				return {
					name: now.toString(),
					value: [
						[now.getFullYear(), now.getMonth() + 1, now.getDate()].join('-')+' '+[now.getHours(), now.getMinutes(), now.getSeconds()].join(':'),
						value,
						Math.random()*100
					]
				}
			}
			for (i =-120; i < 0; i++) {
				dataRead.push(beforerandomData());
			}
			dataRead.push(beforerandomDataread());
			function beforerandomData() {
				nowtime = new Date(+ctime + oneDay*i);
				return {
					name: nowtime.toString(),
					value: [
						[nowtime.getFullYear(), nowtime.getMonth() + 1, nowtime.getDate()].join('-')+' '+[nowtime.getHours(), nowtime.getMinutes(), nowtime.getSeconds()].join(':'),
						0,
						0,
						0
					]
				}
			}
			function beforerandomDataread() {
				nowtime = new Date(+ctime);
				return {
					name: nowtime.toString(),
					value: [
						[nowtime.getFullYear(), nowtime.getMonth() + 1, nowtime.getDate()].join('-')+' '+[nowtime.getHours(), nowtime.getMinutes(), nowtime.getSeconds()].join(':'),
						Math.random()*100,
						Math.random()*100
					]
				}
			}
			var myChartRead = echarts.init(document.getElementById(divid));
			var optionRead = {
				title: {
					show: false
				},
				tooltip: {
					trigger: 'axis',
					formatter: function (params) {
						params = params[0];
						var date = new Date(params.name);
						return date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds()+ ' ' + params.value[2] + 'MB/S';
					},
					axisPointer: {
						animation: false,
					},
					padding: 10,
					extraCssText: 'text-indent: 0;',
					backgroundColor:'#4cae5c'
				},
				xAxis: {
					type: 'time',
					splitLine: {
						show: false
					},
					axisLine: {
						lineStyle: {
							color: '#ddd',
							width: 3
						}
					},
					axisTick:{
						show:false
					},
					axisLabel:{
						textStyle:{
							color:'#eee',
							fontSize: 12,
						}
					}
				},
				yAxis: {
					type: 'value',
					boundaryGap: [0, '100%'],
					splitLine: {
						show: true,
						lineStyle:{
							color:'#666'
						}
					},
					axisLine:{
						lineStyle: {
							color: '#ddd',
							width: 2
						}
					},
					axisTick:{
						show:false
					},
					axisLabel:{
						textStyle:{
							color:'#eee',
							fontSize: 14,
						}
					}
				},
				series: [{
					name: '模拟数据',
					type: 'line',
					symbol:'circle',
					symbolSize:10,
					itemStyle:{
						normal:{
							color:'#4cae5c'
						}
					},
					areaStyle: {
						normal:{
							color:'#2f3351'
						}
					},
					showSymbol: false,
					hoverAnimation: false,
					data: dataRead
				}]
			};
			myChartRead.setOption(optionRead);
			var sh = setInterval(refreshFun,2000);
			function refreshFun(){
				dataRead.shift();
				dataRead.push(readData());
				myChartRead.setOption({
					series: [{
						data: dataRead
					}]
				});
			}
		};
		
		
		// 饼图函数
		this.eCharts = function(divid) {
			var myChart = echarts.init(document.getElementById(divid));
			var option = {
				tooltip: {
					trigger: 'item',
					formatter: "{a} <br/>{b}: {c} ({d}%)"
				},
				legend: {
					orient: 'vertical',
					x: 'left',
				},
				series: [
					{
						name:'应用个数',
						type:'pie',
						radius: ['50%', '70%'],
						avoidLabelOverlap: false,
						label: {
							normal: {
								show: false,
								position: 'center'
							},
							emphasis: {
								show: false,
								textStyle: {
									fontSize: '20',
									fontWeight: 'bold'
								}
							}
						},
						labelLine: {
							normal: {
								show: false
							}
						},
						data:[
							{value:17, name:'运行应用'},
							{value:3, name:'未运行应用'}
						]
					}
				]
			};
			myChart.setOption(option);
		};

		this.eChartsCircle = function(divid) {
			var myChart = echarts.init(document.getElementById(divid));
			var option = {
				title : {
					text: '缺陷基本信息',
					subtext: '纯属虚构',
					x:'center'
				},
				tooltip : {
					trigger: 'item',
					formatter: "{a} <br/>{b} : {c} ({d}%)"
				},
				legend: {
					orient: 'vertical',
					left: 'left',
					data: ['直接访问','邮件营销','联盟广告','视频广告','搜索引擎']
				},
				series : [
					{
						name: '访问来源',
						type: 'pie',
						radius : '55%',
						center: ['50%', '60%'],
						data:[
							{value:335, name:'直接访问'},
							{value:310, name:'邮件营销'},
							{value:234, name:'联盟广告'},
							{value:135, name:'视频广告'},
							{value:1548, name:'搜索引擎'}
						],
						itemStyle: {
							emphasis: {
								shadowBlur: 10,
								shadowOffsetX: 0,
								shadowColor: 'rgba(0, 0, 0, 0.5)'
							}
						}
					}
				]
			};
			myChart.setOption(option);
		}

		// 柱型图函数
		// var eChartBar = function(legends, xAxis, series, divid) {
		this.eChartBar = function(divid) {
			var myChart = echarts.init(document.getElementById(divid));
			var option = {
				tooltip : {
					trigger : 'axis',
					axisPointer : { // 坐标轴指示器，坐标轴触发有效
						type : 'shadow' // 默认为直线，可选为：'line' | 'shadow'
					}
				},
				grid : {
					left : '3%',
					right : '4%',
					bottom : '3%',
					containLabel : true
				},
				xAxis : [ {
					type : 'category',
					// data : xAxis
					data : ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
				} ],
				yAxis : [ {
					type : 'value'
				} ],
				// series : series
				series :[{
							name:'直接访问',
							type:'bar',
							barWidth: '60%',
							data:[10, 52, 200, 334, 390, 330, 220]
				}]
			};
			myChart.setOption(option);
		}
		var monthLastDay = function(month){
			var monthTem = month.substring(5);
//			var monthTem = month.split('/')[1];
			if(monthTem==="01"||monthTem==="03"||monthTem==="05"||monthTem==="07"||monthTem==="08"||monthTem==="10"||monthTem==="12"){
				return '/31';
			}
			if(monthTem==="04"||monthTem==="06"||monthTem==="09"||monthTem==="11"){
				return '/30';
			}
			if(monthTem==="02"){
				return '/28';
			}
		}
		
		//时间参数
		this.addTimepara = function(params,beginDate,endDate){
      //'2016/11
		      if(beginDate!==''){
		        params.push(this.construcPara('beginDate', beginDate+'/01'));
		      }
		      if(endDate!==''){
		        params.push(this.construcPara('endDate', endDate+monthLastDay(endDate)));
		      }
		    };
		    
		// 图表数据
		this.constructChartData = function(rows, name) {
			var dimensions = [ 'instanceNum', 'fee', 'cpuNum', 'memoryDrp',
					'diskDrp' ];
			var userDataFlag = false;
			if(rows.length===0){
				userDataFlag = false;
			}else{
				userDataFlag = !!!rows[0].name;
			}
			var legends = this.filterData(rows, 'name', userDataFlag);
			var xAxis = this.filterData(rows, 'meterDate', userDataFlag);
			var formatXAxis = [];
			$.each(xAxis, function(index, value) {
				formatXAxis.push(value.substring(0, 7));
			});
			var dimensionSeries;
			$.each(dimensions, function(index, dimension) {
				dimensionSeries = constructSeriesData(rows, legends, dimension,
						userDataFlag);
				eChartBar(legends, formatXAxis, dimensionSeries, name + index);
			});
		}
		
		// 提取单个数据
		this.filterData = function(rows, key, userDataFlag) {
			var results = [];
			var value;
			$.each(rows, function(index, rowData) {
				if ('name' === key && userDataFlag) {
					value = rowData.instanceName;
				} else {
					value = rowData[key];
				}
				if (-1 == results.indexOf(value)) {
					results.push(value);
				}
			});
			return results;
		};

		// 构建series数据
		var constructSeriesData = function(rows, legends, key, userDataFlag) {
			var results = [];
			var serieArr = [];
			var serieObj;
			$.each(legends, function(index, legendName) {
				serieArr = [];
				serieObj = {
					name : legendName,
					type : 'bar'
				};
				$.each(rows, function(index, rowData) {
					if (userDataFlag && legendName === rowData.instanceName) {
						serieArr.push(rowData[key]);
					} else if (legendName === rowData.name) {
						serieArr.push(rowData[key]);
					}
				});
				serieObj.data = serieArr;
				results.push(serieObj);
			});
			return results;
		}
		this.exportExcel = function(url, para) {
			document.getElementById("testExport").setAttribute("src",
					url + "?params=" + para);
		};
	});
})();